package com.spc.boot.common.config;
import com.spc.boot.common.security.CustomUserDetailsService;
import com.spc.boot.common.security.JwtAuthenticationTokenFilter;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.security.config.annotation.authentication.builders.AuthenticationManagerBuilder;
import org.springframework.security.config.annotation.method.configuration.EnableGlobalMethodSecurity;
import org.springframework.security.config.annotation.web.builders.HttpSecurity;
import org.springframework.security.config.annotation.web.configuration.EnableWebSecurity;
import org.springframework.security.config.annotation.web.configuration.WebSecurityConfigurerAdapter;
import org.springframework.security.crypto.bcrypt.BCryptPasswordEncoder;
import org.springframework.security.crypto.password.PasswordEncoder;



@EnableWebSecurity
@Configuration
@EnableGlobalMethodSecurity(prePostEnabled = true)
public class SecurityConfig extends WebSecurityConfigurerAdapter {

    @Autowired
    CustomUserDetailsService customUserDetailsService;



    @Autowired
    JwtAuthenticationTokenFilter jwtAuthenticationTokenFilter;

    //使用原生加密组件,可直接使用
    @Bean
    public PasswordEncoder passwordEncoder() {
        return new BCryptPasswordEncoder();
    }

    @Override
    protected void configure(HttpSecurity http) throws Exception {

        http

                //除登录注册页面,其他页面访问均需鉴权
                .authorizeRequests()
                .antMatchers("/account/login","/account/apiLogin","/account/doRegister","/account/register").permitAll()
                .anyRequest().authenticated()

                //使用form表单post方式进行登录
                .and()
                .formLogin()
                //登录页面为自定义的登录页面
                .loginPage("/account/login")
                //设置登录成功跳转页面，error=true控制页面错误信息的展示
                .successForwardUrl("/login_success").failureUrl("/account/login?error=true")
                .permitAll()

                // 自定义登出动作
                .and().logout().logoutSuccessUrl("/account/login")

                .and().csrf().disable();;

    }


    @Override
    public void  configure(AuthenticationManagerBuilder auth) throws Exception {
        //使用自定义的密码获取service
        auth.userDetailsService(customUserDetailsService);
    }
}
